package org.zxyj.core.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.zxyj.core.entity.Pagination;

public class PageInterceptor extends HandlerInterceptorAdapter {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {  
    	try {
			initParam(request, response);
		} catch (Exception e) {
			logger.debug("拦截器PageInterceptor处理分页参数出错", e);
		}
        return true;
    }
    
    /**
	 * 分页参数处理
	 * @param controller
	 * @param superControllerClass
	 */
	public void initParam(HttpServletRequest request, HttpServletResponse response) {
		Pagination pagination = new Pagination();
		
		// 每页显示几多
		String pageSize = request.getParameter(Pagination.PAGESIZE_KEY);
		if(!StringUtils.isEmpty(pageSize)){
			logger.debug("分页，每页显示几多：pageSize = [{}]", pageSize);
		} else {
			pageSize = Pagination.DEFAULT_PAGESIZE + "";
		}
		pagination.setPageSize(Integer.parseInt(pageSize));
		
		// 第几页
		String current = request.getParameter(Pagination.CURRENT_KEY);
		HttpSession session = request.getSession();
		if(!StringUtils.isEmpty(current)) {
			logger.debug("分页，第几页：pageNumber = [{}]", current);
			session.setAttribute(request.getRequestURL() + Pagination.CURRENT_KEY, current);
		} else {
			current = (String) session.getAttribute(request.getRequestURL() + Pagination.CURRENT_KEY);
		}
		
		if(!StringUtils.isEmpty(current)) {
			pagination.setCurrent(Integer.parseInt(current));
		}
		request.setAttribute("pagination", pagination);
	}
    
}
